/**
 * ajax请求配置
 */
import axios from 'axios'

// axios默认配置
let baseProject = process.env.VUE_APP_URL;
axios.defaults.timeout = 9000;   // 超时时间
axios.defaults.baseURL = baseProject;  // 默认地址

//整理数据
axios.defaults.transformRequest = function (data) {
    data = JSON.stringify(data);
    return data;
};

// http request 拦截器
axios.interceptors.request.use(
    config => {
        let accessToken = localStorage.getItem("accessToken");
        config.headers['Content-Type'] = 'application/json;charset=UTF-8';
        config.headers['X-Access-Token'] = accessToken;
        return config;
    },
    error => {
        return Promise.reject(error.response);
    });

const responseError = (error) => {
    if (error.response) {
        let data = error.response.data
        // const accessToken = localStorage.getItem("accessToken");
        switch (error.response.status) {
            case 403:
                alert("拒绝访问");
                break
            case 500:
                alert(data.message);
                break
            case 404:
                alert("很抱歉，资源未找到");
                break
            case 504:
                alert("网络超时");
                break
            case 401:
                alert("未授权，请重新登录");
                break
            default:
                alert(data.message);
                break
        }
    }
    return Promise.reject(error)
};

// http response 拦截器
axios.interceptors.response.use((response) => {
    return response.data
}, responseError)

export default axios;
